package com.hunlian.makelove.common;



import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ContextUtils {

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 * @throws NameNotFoundException 
	 */
	public static String getVersion(Context context,int id) {

		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
			String version = info.versionCode+"";
			return version;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return context.getString(id); 

		}
	}
	
	/**
	 * 将yyyy-M-d转成yyyy-MM-dd
	 * @author zj
	 * @return yyyy-MM-dd
	 */
	public static String dateToString(String date) {
		String time = null;
		try {
			SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
			Date str = formatDate.parse(date);

					
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			time = format.format(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return time;
	}
	
	/**
	 * 获取屏幕的宽度 高度 密度 dpi
	 * @param activity
	 * @return float[] 屏幕的宽度 高度 密度 dpi
	 */
	public static float[] getPhoneDensity(Activity activity){
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）
        int height = metric.heightPixels;  // 屏幕高度（像素）
        float density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
        float[] parameters = {width,height,density,densityDpi};
        return parameters;
	}
	
	/**
	 * 在sd卡下创建文件夹
	 * @param dirPath 文件夹的路径和名称 
	 * @return 成功创建返回true，否则返回false
	 */
	public static boolean makeDirs(String dirPath){
		
		if(!dirPath.toLowerCase().contains("sdcard"))
			dirPath = "sdcard/"+dirPath;
		File file = new File(dirPath);
	    if(!file.exists()){
		      file.mkdirs();
		      return true;
		}
		return false;
	}
	
	
	/** 
	* 递归删除文件和文件夹 
	* 
	* @param file 
	* 要删除的根目录 
	*/ 
	public static void DeleteFile(File file) { 
		
		if (file.exists() == false) { 
			return; 
		} else { 
			if (file.isFile()) { 
				file.delete(); 
				return; 
			} 
			if (file.isDirectory()) { 
				File[] childFile = file.listFiles(); 
				if (childFile == null || childFile.length == 0) { 
					file.delete(); 
					return; 
				} 
				for (File f : childFile) { 
					DeleteFile(f); 
				} 
				file.delete(); 
			}
		}
	}
	
	/**
	 * 获取程序图片文件夹的路径  "sdcard/VZPics/record/"
	 * @param context
	 * @return  "sdcard/VZPics/record/"
	 */
	public static String getPicDirName(Context context){
		String path = "HLW_Pics/record";
		
		return Environment.getExternalStorageDirectory()+
		File.separator+path+File.separator;
	}
	
	/**
	 * 获取程序图片文件夹的路径  "sdcard/VZPics/website/net"
	 * @param context
	 * @return  "sdcard/VZPics/website/net"
	 */
	public static String getWebsiteSearchPicDirName(Context context){
		String path = "HLW_Pics/website/net";
		
		return Environment.getExternalStorageDirectory()+
		File.separator+path+File.separator;
	}
	
	/**
	 * 获取程序图片文件夹的路径  "sdcard/VZPics/website/photoAlbum/"
	 * @param context
	 * @return  "sdcard/VZPics/website/photoAlbum/"
	 */
	public static String getPhotoAlbumDirName(Context context){
		String path = "HLW_Pics/website/photoAlbum";
		
		return Environment.getExternalStorageDirectory()+
		File.separator+path+File.separator;
	}
	
	/**
	 * 获取程序图片文件夹的路径  "sdcard/VZPics/website/photoAlbum/small/"
	 * @param context
	 * @return  "sdcard/VZPics/website/photoAlbum/small/"
	 */
	public static String getPhotoAlbumSmallDirName(Context context){
		String path = "HLW_Pics/website/photoAlbum/small";
		
		return Environment.getExternalStorageDirectory()+
		File.separator+path+File.separator;
	}
	
	/**
	 * 获取程序图片文件夹的路径  "sdcard/VZPics/website/photoAlbum/big/"
	 * @param context
	 * @return  "sdcard/VZPics/website/photoAlbum/big/"
	 */
	public static String getPhotoAlbumBigDirName(Context context){
		String path = "HLW_Pics/website/photoAlbum/big";
		
		return Environment.getExternalStorageDirectory()+
		File.separator+path+File.separator;
	}
	
	/**
	 * 获取程序图片文件夹的路径  "sdcard/VZPics/website/take"
	 * @param context
	 * @return  "sdcard/VZPics/website/take"
	 */
	public static String getWebsiteSearchTakePicDirName(Context context){
		String path = "HLW_Pics/website/take";
		
		return Environment.getExternalStorageDirectory()+
		File.separator+path+File.separator;
	}
	
	/**
	 * 获取程序图片文件夹的路径  "sdcard/path/"
	 * @param context
	 * @param path
	 * @return  "sdcard/path/"
	 */
	public static String getPicDirName(Context context,String path){

		System.out.println("Environment.getExternalStorageDirectory(): "+Environment.getExternalStorageDirectory());
		//System.out.println("File.separator: "+File.separator);

		String sysDir;
		if(Environment.getExternalStorageDirectory().equals("/sdcard")==false){
			sysDir = "/sdcard";
		}else{
			sysDir = Environment.getExternalStorageDirectory()+"";
		}
		return sysDir+ File.separator+path+File.separator;

	}
	
	/**
	 * 刷新系统相册
	 */
	public  static void refreshSysPhotoAlbum(Context context){
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory())));
	}
	
	/**
	 * 刷新本地相册
	 * @param path 相册所在的文件夹的绝对路径
	 */
	public  static void refreshLocalPhotoAlbum(Context context,String path){	
		MediaScannerConnection.scanFile(context, new String[]{path}, null, null);
		//下面的方法4.4以后的版本会报错，弃用@zealjiang 2015-10-28
		//context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + path)));
	}
	
	/**
	 * 复制文件
	 * @param fromFile
	 * @param toFile
	 * @param rewrite 如果toFile存在并且rewrite为true，toFile将被删除
	 */
	public static void copyFile(File fromFile, File toFile,Boolean rewrite){

		if (!fromFile.exists()) {
			return;
		}

		if (!fromFile.isFile()) {	
			return ;	
		}

		if (!fromFile.canRead()) {	
			return ;
		}

		if (!toFile.getParentFile().exists()) {	
			toFile.getParentFile().mkdirs();	
		}

		if (toFile.exists() && rewrite) {
			toFile.delete();
		}

		try {	
			java.io.FileInputStream fosfrom = new java.io.FileInputStream(fromFile);		
			FileOutputStream fosto = new FileOutputStream(toFile);
			byte bt[] = new byte[1024];		
			int c;	
			while ((c = fosfrom.read(bt)) > 0) {	
				fosto.write(bt, 0, c); //将内容写到新文件当中
			}

			fosfrom.close();
		
			fosto.close();
		
		} catch (Exception ex){}
				
	}

	/**弹出软键盘*/
	public void showInputMethod(final EditText editText) {
		editText.setFocusable(true);
		editText.setFocusableInTouchMode(true);
		editText.requestFocus();
		//延迟弹出输入法
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(editText, 0);
			}
		}, 200);
	}

	/**
	 *第一个内容非空的EditText弹出软键盘
	 *@author zealjiang
	 *created at 2016/3/26 21:52
	 */
	public void showInputKeyboard(ArrayList<EditText> list){
		for (int i = 0; i <list.size() ; i++) {
			EditText et = list.get(i);
			if(et==null){
				continue;
			}
			if(StringUtil.isEmpty(et.getText().toString())){
				showInputMethod(et);
				break;
			}
		}
	}
}
